<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="导出数据"
    :footer="null"
    :width="600"
    :height="300"
    :canFullscreen="false"
    :destroyOnClose="true"
    wrapClassName="stationPopup"
    @height-change="handleHeightChange"
  >
    <div class="export-modal-content">
      <div class="rain-type-section">
        <h3 class="section-title">选择降雨类型</h3>
        <div class="rain-select">
          <a-select
            v-model:value="state.selectedRainTypes"
            placeholder="请选择降雨类型"
            class="rain-select-input"
            size="large"
            :options="state.rainOptions"
            mode="multiple"
            @change="handleRainTypeChange"
          />
        </div>
      </div>

      <div class="export-action-section">
        <a-button
          type="primary"
          size="large"
          class="export-btn"
          @click="handleExport"
          :loading="state.exportLoading"
        >
          <template #icon>
            <DownloadOutlined />
          </template>
          导出数据
        </a-button>
      </div>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, reactive, provide } from 'vue';
import { BasicModal, useModalInner } from '@gui-pkg/antdcomponents';
import { DownloadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import axios from "axios";
import dayjs from "dayjs";
import {useUserStoreWithOut} from "@/store/modules/user";

const modalHeightValue = ref(620);
const state = reactive({
  data: null,
  selectedRainTypes: [], // 默认全部，改为数组格式
  exportLoading: false, // 导出加载状态

  // 转换为下拉框需要的格式
  rainOptions: [
    { value: 'rain0', label: '0mm' },
    { value: 'rain1', label: '0.1~10mm' },
    { value: 'rain2', label: '10~25mm' },
    { value: 'rain3', label: '25~50mm' },
    { value: 'rain4', label: '50~100mm' },
    { value: 'rain5', label: '100~250mm' },
    { value: 'rain6', label: '＞250mm' },
    { value: 'nohasRain', label: '设备离线' },
  ]
});

const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
  setModalProps({ confirmLoading: false });
  state.data = data.record;
});

// 弹窗高度变化，主要是监听是否点击了全屏
const handleHeightChange = (height: string) => {
  modalHeightValue.value = height;
};

// 降雨类型选择变化
const handleRainTypeChange = (value: string[]) => {
  console.log('选择的降雨类型:', value);
  state.selectedRainTypes = value;
};

const userStore = useUserStoreWithOut();
const PUBLIC_PATH:string = import.meta.env.VITE_PUBLIC_API;

async function handleExport() {
  if (!state.selectedRainTypes || state.selectedRainTypes.length === 0) {
    message.warning('请选择降雨类型');
    return;
  }
  state.exportLoading = true;
  try {
    let fileName = "过去24小时实况降雨" + dayjs().toISOString();

    // 将数组转换为逗号分隔的字符串，或者直接传递数组（根据后端接口要求）
    const params = state.selectedRainTypes.join(','); // 或者直接传递 state.selectedRainTypes

    axios({
      url: `${PUBLIC_PATH}/api/pptn/st/export`,
      method: "POST",
      responseType: "blob",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: userStore.getToken,
      },
      data: { params }, // 修改参数名，传递数组
    }).then((res) => {
      let url = window.URL.createObjectURL(new Blob([res.data]));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", `${fileName}.xls`);
      document.body.appendChild(link);
      link.click();
      message.success('导出成功');
      closeModal();
    }).catch((error) => {
      console.error('导出失败:', error);
      message.error('导出失败，请重试');
    });
  } catch (e) {
    console.error('导出异常:', e);
    message.error('导出异常，请重试');
  } finally {
    state.exportLoading = false;
  }
}

provide('ModalHeightChange', modalHeightValue);
</script>

<style lang="less" rel="stylesheet/less" scoped>
.export-modal-content {
  padding: 20px;
  height: 100%;
  .rain-type-section {
    margin-bottom: 30px;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 16px;
      text-align: center;
    }

    .rain-select {
      .rain-select-input {
        width: 100%;

        :deep(.ant-select-selector) {
          border-radius: 8px;
          border: 2px solid #e8e8e8;
          transition: all 0.3s;
          min-height: 48px;
          display: flex;
          align-items: center;
          flex-wrap: wrap;

          &:hover {
            border-color: #40a9ff;
          }
        }

        :deep(.ant-select-selection-placeholder) {
          color: #999;
          font-size: 14px;
        }

        :deep(.ant-select-selection-item) {
          font-size: 14px;
          font-weight: 500;
          background: #f0f8ff;
          border: 1px solid #1890ff;
          border-radius: 4px;
          margin: 2px 4px 2px 0;
        }
      }

      :deep(.ant-select-focused .ant-select-selector) {
        border-color: #1890ff !important;
        box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
      }
    }
  }

  .export-action-section {
    text-align: center;

    .export-btn {
      height: 50px;
      font-size: 16px;
      font-weight: 600;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
      transition: all 0.3s;
      background: linear-gradient(135deg, #1890ff, #096dd9);
      border: none;
      min-width: 200px;

      &:hover {
        box-shadow: 0 6px 16px rgba(24, 144, 255, 0.6);
        transform: translateY(-2px);
        background: linear-gradient(135deg, #40a9ff, #1890ff);
      }

      &:active {
        transform: translateY(0);
        box-shadow: 0 2px 8px rgba(24, 144, 255, 0.4);
      }

      &:disabled {
        background: #f5f5f5;
        box-shadow: none;
        transform: none;
        cursor: not-allowed;
      }

      :deep(.ant-btn-loading-icon) {
        margin-right: 8px;
      }
    }
  }
}

// 响应式调整
@media (max-height: 450px) {
  .export-modal-content {
    padding: 16px;

    .rain-type-section {
      margin-bottom: 24px;
    }

    .export-action-section {
      .export-btn {
        height: 44px;
        font-size: 15px;
        min-width: 180px;
      }
    }
  }
}

// 下拉框选项样式调整
:deep(.ant-select-dropdown) {
  .ant-select-item {
    padding: 12px 16px;
    font-size: 14px;

    &.ant-select-item-option-active {
      background-color: #f0f8ff;
    }

    &.ant-select-item-option-selected {
      background-color: #e6f7ff;
      font-weight: 500;
    }
  }
}
</style>
